function generateQR() {
    const content = document.getElementById('content').value;
    if (!content) {
        showToast('请输入内容');
        return;
    }

    const size = parseInt(document.getElementById('size').value);
    const errorLevel = document.getElementById('errorLevel').value;
    const qrcodeDiv = document.getElementById('qrcode');
    
    // 清空之前的二维码
    qrcodeDiv.innerHTML = '';

    // 创建新的 QRCode 实例
    new QRCode(qrcodeDiv, {
        text: content,
        width: size,
        height: size,
        colorDark: "#000000",
        colorLight: "#ffffff",
        correctLevel: QRCode.CorrectLevel[errorLevel]
    });
}

function downloadQR() {
    const qrImage = document.querySelector('#qrcode img');
    if (!qrImage) {
        showToast('请先生成二维码');
        return;
    }

    // 创建一个临时的 canvas 来处理图片下载
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');
    canvas.width = qrImage.width;
    canvas.height = qrImage.height;
    
    // 等待图片加载完成后再绘制到 canvas
    qrImage.onload = function() {
        ctx.drawImage(qrImage, 0, 0);
        const link = document.createElement('a');
        link.download = 'qrcode.png';
        link.href = canvas.toDataURL('image/png');
        link.click();
        showToast('二维码已下载');
    };
    
    // 如果图片已经加载完成，直接触发 onload
    if (qrImage.complete) {
        qrImage.onload();
    }
}

function showToast(message) {
    const toast = document.getElementById('toast');
    toast.textContent = message;
    toast.classList.add('show');
    setTimeout(() => {
        toast.classList.remove('show');
    }, 2000);
} 